<script setup lang='ts'>
import Sortable from 'sortablejs'
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const list = ref([
  {
    id: 1,
    name: "哪吒之魔童降世",
    area: "中国",
    type: "动画",
    one: "50亿",
    two: "100亿",
    three: "150亿",
  },
  {
    id: 2,
    name: "哪吒之魔童闹海",
    area: "中国",
    type: "动画",
    one: "20亿",
    two: "40亿",
    three: "40亿",
  },
  {
    id: 3,
    name: "复仇者联盟",
    area: "美国",
    type: "科幻",
    one: "100亿",
    two: "200亿",
    three: "300亿",
  },
  {
    id: 4,
    name: "复仇者联盟2",
    area: "美国",
    type: "科幻",
    one: "100亿",
    two: "200亿",
    three: "200亿",
  },
  {
    id: 5,
    name: "复仇者联盟3",
    area: "美国",
    type: "科幻",
    one: "300亿",
    two: "300亿",
    three: "300亿",
  }
])

const refresh = ref(true)

const rowDrop = () => {
  const tbody = document.querySelector('.el-table__body-wrapper tbody') // 找到创建sortable的dom
  Sortable.create(tbody, {
    animation: 150,
    ghostClass: "sortable-ghost",  // drop placeholder的css类名
    chosenClass: "sortable-chosen",  // 被选中项的css 类名
    forceFallback: false,  // 忽略 HTML5拖拽行为，强制回调进行
    onEnd: ({ newIndex, oldIndex }) => { // 因为只是普通的列表拖拽 我们只需要在结束拖拽的时候做数据源的梳理
      // 删除当前行，放到拖拽后的位置
      const targetRow = list.value.splice(oldIndex, 1)[0]
      list.value.splice(newIndex, 0, targetRow)

      let newArr = list.value.slice(0) // 深拷贝

      list.value = [] // 清空数据源 并重新赋值
      nextTick(() => {
        list.value = newArr
      })
    }
  })
}

onMounted(() => {
  rowDrop()
})

</script>


<template>
  <el-table
    :data="list"
    row-key="id"
    style="width: 100%"
    border
  >
    <el-table-column prop="name" label="电影名" />
    <el-table-column prop="area" label="地区" />
    <el-table-column prop="type" label="类型" />
    <el-table-column prop="one" label="第一季度票房" />
    <el-table-column prop="two" label="第二季度票房" />
    <el-table-column prop="three" label="第三季度票房" />
  </el-table>
  <el-button @click="router.back()" style="margin-top: 50px;">返回</el-button>
</template>


<style scoped lang="scss">
  ::v-deep(.el-table__body-wrapper) {
  .sortable-ghost {
    opacity: .8;
    background: #42b983 !important;
    
    td {
      background: transparent !important;
    }
  }

  .sortable-chosen {
    background: #42b983 !important;
    
    td {
      background: transparent !important;
    }
  }
}
</style>